package org.sq;

import java.util.ArrayList;
import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class TabsActivity extends ActionBarActivity implements
		ActionBar.TabListener {

	ViewPager mViewPager;
	MyAdapter mAdapter;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private ArrayList<Quest> questList;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final LevelManager levelManager = ((SQApp)getApplicationContext()).levelManager();
		if(!levelManager.isInit()){
			loadGame();
		}
		
		
		setContentView(R.layout.activity_tabs);
		final ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		mTitle = mDrawerTitle = getTitle();
		questList = levelManager.getQuests();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		// set up the drawer's list view with items and click listener
		mDrawerList.setAdapter(drawerListAdapter);
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		// enable ActionBar app icon to behave as action to toggle nav drawer
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setHomeButtonEnabled(true);

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				actionBar.setTitle(mTitle);
				ActivityCompat.invalidateOptionsMenu(TabsActivity.this); // creates
																			// call
																			// to
				// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				drawerListAdapter.notifyDataSetChanged();
				hideKeyboard();
				actionBar.setTitle(mDrawerTitle);
				ActivityCompat.invalidateOptionsMenu(TabsActivity.this); // creates
																			// call
																			// to
				// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			selectItem(0);
		}

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);

	
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
						hideKeyboard();
					}
				});
		// For each of the sections in the app, add a tab to the action bar.
		
		
		reloadFragments();

	}
	
	
	
	
	public void reloadFragments(){
		ArrayList<Fragment> mFragments;
		mFragments = new ArrayList<Fragment>();
		Fragment f = new NavigationFragment();
		mFragments.add(f);
		f = new QuestFragment();
		mFragments.add(f);
		f = new StatusFragment();
		mFragments.add(f);

		mAdapter = new MyAdapter(getSupportFragmentManager(), mFragments);

		mViewPager.setAdapter(mAdapter);
		final ActionBar actionBar = getSupportActionBar();
		actionBar.removeAllTabs();
		for (int i = 0; i < mAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab()
					.setText(mAdapter.getPageTitle(i)).setTabListener(this));
		}
	}

	protected void hideKeyboard() {
		try {
			InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {

		}

	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			selectItem(position);
		}
	}

	private void selectItem(int position) {
		final LevelManager levelManager = ((SQApp)getApplicationContext()).levelManager();

		Quest q = questList.get(position);
		mDrawerLayout.closeDrawer(mDrawerList);
		
		if(levelManager.isLevelClosed(q) || q.isCompleted()){
			return;
		}
		// update selected item and title, then close the drawer
		mDrawerList.setItemChecked(position, true);
		levelManager.setCurrentQuest(questList.get(position));
		if (mViewPager != null)
			reloadFragments();
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getSupportActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	public class MyAdapter extends FragmentStatePagerAdapter {
		ArrayList<Fragment> mFragments;

		public MyAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
			super(fm);
			mFragments = fragments;

		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public Fragment getItem(int position) {
			// Bundle args = new Bundle();
			Fragment f = mFragments.get(position);
			// f.setArguments(args);
			return f;
		}

		@Override
		public CharSequence getPageTitle(int position) {

			switch (position) {
			case 0:
				return TabsActivity.this.getResources().getString(
						R.string.tab_title_1);
			case 1:
				return TabsActivity.this.getResources().getString(
						R.string.tab_title_2);
			case 2:
				return TabsActivity.this.getResources().getString(
						R.string.tab_title_3);
			}
			return null;
		}

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.about, menu);
		return true;
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		hideKeyboard();
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setTitle(getString(R.string.exit_dialog_title));
		builder.setMessage(getString(R.string.exit_dialog_message));
		builder.setPositiveButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						dialog.dismiss();
					}
				});
		builder.setNegativeButton(getString(R.string.no),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	BaseAdapter drawerListAdapter = new BaseAdapter() {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return questList.size();
		}

		@Override
		public Quest getItem(int position) {
			// TODO Auto-generated method stub
			return questList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final LevelManager levelManager = ((SQApp)getApplicationContext()).levelManager();

			View view = convertView;
			if (view == null) {
				LayoutInflater lInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = lInflater.inflate(R.layout.drawer_list_item, parent,
						false);
			}
			TextView textView = (TextView) view;
			Quest q = getItem(position);
			textView.setText(q.getTitle());
			if (q.isCompleted()) {
				textView.setBackgroundResource(R.drawable.level_completed);
			} else if(levelManager.isLevelClosed(q)){
				textView.setBackgroundResource(R.drawable.level_closed);
			} else {
				textView.setBackgroundResource(R.drawable.level_open);
			}
			return view;
		}

	};
	
	void loadGame() {
		final LevelManager levelManager = ((SQApp) getApplicationContext()).levelManager();
		try {
			levelManager.restoreQuests();
			if (!levelManager.readNextLevel()) {
				if (!levelManager.readFirstLevel()) {
					return;
				}
			}

			Intent intent = new Intent(this, TabsActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			Log.e("Error", "" + e.getLocalizedMessage());
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(true);
			builder.setTitle(getString(R.string.error));
			builder.setMessage(getString(R.string.file_format_error));
			builder.setPositiveButton(getString(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();

						}
					});

			AlertDialog alert = builder.create();
			alert.show();
		}
	}

}
